<template>
  <div class="exam-list-container">
    <div class="header">
      <h2>考试管理</h2>
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入考试名称"
          prefix-icon="Search"
          style="width: 300px; margin-right: 10px;"
        />
        <el-button type="primary" @click="searchExams">
          <el-icon><Search /></el-icon> 搜索
        </el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div class="action-buttons">
        <el-button type="primary" @click="openAddDialog">
          <el-icon><Plus /></el-icon> 新增
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
        <el-button @click="downloadData">
          <el-icon><Download /></el-icon> 导出
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="examList"
      style="width: 100%;"
      border
    >
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="title" label="考试名称" width="200" />
      <el-table-column prop="category" label="分类" width="120" align="center" />
      <el-table-column prop="questionCount" label="题目数量" width="100" align="center" />
      <el-table-column prop="duration" label="时长(分钟)" width="100" align="center" />
      <el-table-column prop="totalScore" label="总分" width="80" align="center" />
      <el-table-column prop="passScore" label="及格分" width="80" align="center" />
      <el-table-column prop="startTime" label="开始时间" width="180" align="center" :formatter="formatDate" />
      <el-table-column prop="endTime" label="结束时间" width="180" align="center" :formatter="formatDate" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag
            :type="row.status === 1 ? 'success' : row.status === 0 ? 'info' : 'warning'"
          >
            {{ row.status === 1 ? '启用' : row.status === 0 ? '禁用' : '未知' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right" align="center">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="openEditDialog(row)">
            <el-icon><Edit /></el-icon> 编辑
          </el-button>
          <el-button type="success" size="small" @click="manageQuestions(row.id)">
            <el-icon><Document /></el-icon> 题目
          </el-button>
          <el-button type="warning" size="small" @click="viewScores(row.id)">
            <el-icon><DataAnalysis /></el-icon> 成绩
          </el-button>
          <el-button type="danger" size="small" @click="deleteExam(row.id)">
            <el-icon><Delete /></el-icon> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" :title="dialogType === 'add' ? '新增考试' : '编辑考试'" width="600px">
      <el-form
        ref="examFormRef"
        :model="examForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="考试名称" prop="title">
          <el-input v-model="examForm.title" placeholder="请输入考试名称" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="examForm.category" placeholder="请选择分类">
            <el-option label="前端开发" value="前端开发" />
            <el-option label="后端开发" value="后端开发" />
            <el-option label="移动开发" value="移动开发" />
            <el-option label="人工智能" value="人工智能" />
          </el-select>
        </el-form-item>
        <el-form-item label="时长(分钟)" prop="duration">
          <el-input v-model.number="examForm.duration" type="number" placeholder="请输入考试时长" />
        </el-form-item>
        <el-form-item label="总分" prop="totalScore">
          <el-input v-model.number="examForm.totalScore" type="number" placeholder="请输入总分" />
        </el-form-item>
        <el-form-item label="及格分" prop="passScore">
          <el-input v-model.number="examForm.passScore" type="number" placeholder="请输入及格分" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="examForm.startTime" type="datetime" placeholder="请选择开始时间" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="examForm.endTime" type="datetime" placeholder="请选择结束时间" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="examForm.status" placeholder="请选择状态">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="examForm.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveExam">确定</el-button>
      </template>
    </el-dialog>

    <!-- 题目管理对话框 -->
    <el-dialog v-model="questionDialogVisible" title="题目管理" width="900px" height="600px">
      <div class="question-management">
        <div class="question-toolbar">
          <el-button type="primary" @click="openQuestionEditDialog(null)">
            <el-icon><Plus /></el-icon> 添加题目
          </el-button>
          <el-button @click="refreshQuestions">
            <el-icon><Refresh /></el-icon> 刷新
          </el-button>
        </div>
        
        <el-table :data="questions" style="width: 100%;" border>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="type" label="类型" width="100">
            <template #default="{ row }">
              <el-tag :type="row.type === 'single' ? 'primary' : row.type === 'multiple' ? 'success' : 'warning'">
                {{ row.type === 'single' ? '单选题' : row.type === 'multiple' ? '多选题' : '简答题' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="题目" show-overflow-tooltip />
          <el-table-column prop="score" label="分数" width="80" />
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="openQuestionEditDialog(row)">编辑</el-button>
              <el-button type="danger" size="small" @click="deleteQuestion(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <template #footer>
        <el-button @click="questionDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 题目编辑对话框 -->
    <el-dialog v-model="questionEditDialogVisible" :title="currentQuestion.id ? '编辑题目' : '新增题目'" width="700px">
      <el-form
        ref="questionFormRef"
        :model="currentQuestion"
        :rules="questionRules"
        label-width="100px"
      >
        <el-form-item label="题目类型" prop="type">
          <el-select v-model="currentQuestion.type" placeholder="请选择题目类型">
            <el-option label="单选题" value="single" />
            <el-option label="多选题" value="multiple" />
            <el-option label="简答题" value="text" />
          </el-select>
        </el-form-item>
        <el-form-item label="题目内容" prop="title">
          <el-input v-model="currentQuestion.title" type="textarea" :rows="3" placeholder="请输入题目内容" />
        </el-form-item>
        <el-form-item label="分数" prop="score">
          <el-input v-model.number="currentQuestion.score" type="number" placeholder="请输入分数" />
        </el-form-item>
        
        <!-- 选项部分 (单选/多选题) -->
        <div v-if="currentQuestion.type !== 'text'">
          <el-divider>选项设置</el-divider>
          <el-form-item 
            v-for="(option, index) in currentQuestion.options" 
            :key="index"
            :label="`选项${String.fromCharCode(65 + index)}`"
          >
            <el-input v-model="option.content" placeholder="请输入选项内容">
              <template #append>
                <el-button @click="removeOption(index)">删除</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="addOption">添加选项</el-button>
          </el-form-item>
          
          <!-- 正确答案 (单选题) -->
          <el-form-item v-if="currentQuestion.type === 'single'" label="正确答案">
            <el-radio-group v-model="currentQuestion.correctAnswer">
              <el-radio 
                v-for="(option, index) in currentQuestion.options" 
                :key="index"
                :label="String.fromCharCode(65 + index)"
              >
                {{ String.fromCharCode(65 + index) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          
          <!-- 正确答案 (多选题) -->
          <el-form-item v-if="currentQuestion.type === 'multiple'" label="正确答案">
            <el-checkbox-group v-model="currentQuestion.correctAnswers">
              <el-checkbox 
                v-for="(option, index) in currentQuestion.options" 
                :key="index"
                :label="String.fromCharCode(65 + index)"
              >
                {{ String.fromCharCode(65 + index) }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
        
        <!-- 答案部分 (简答题) -->
        <div v-else>
          <el-divider>参考答案</el-divider>
          <el-form-item label="参考答案">
            <el-input v-model="currentQuestion.referenceAnswer" type="textarea" :rows="4" placeholder="请输入参考答案" />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="questionEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveQuestion">确定</el-button>
      </template>
    </el-dialog>

    <!-- 成绩管理对话框 -->
    <el-dialog v-model="scoreDialogVisible" title="考试成绩" width="900px">
      <div class="score-management">
        <div class="score-header">
          <el-button type="primary" @click="exportScores">
            <el-icon><Download /></el-icon> 导出成绩
          </el-button>
          <div class="score-stats">
            <span>总人数: {{ scoreStats.total }}</span>
            <span>及格人数: {{ scoreStats.passed }}</span>
            <span>平均分: {{ scoreStats.average }}</span>
          </div>
        </div>
        
        <el-table :data="scores" style="width: 100%;" border>
          <el-table-column prop="userId" label="用户ID" width="100" />
          <el-table-column prop="username" label="用户名" width="150" />
          <el-table-column prop="score" label="得分" width="100" />
          <el-table-column prop="usedTime" label="用时(分钟)" width="120" />
          <el-table-column prop="submitTime" label="提交时间" width="180" :formatter="formatDateTime" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '及格' : '不及格' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <template #footer>
        <el-button @click="scoreDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElTable, ElTableColumn, ElButton, ElIcon, ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElPagination, ElMessageBox, ElNotification, ElDatePicker, ElSwitch, ElTag, ElDivider, ElRadioGroup, ElRadio, ElCheckboxGroup, ElCheckbox } from 'element-plus'
import { Search, Plus, Edit, Delete, Refresh, Download, Filter, Check, Close, Clock, Document, DataAnalysis } from '@element-plus/icons-vue'
import { getExamPage, saveOrUpdateExam, deleteExams, getExamById, getExamQuestions, saveOrUpdateQuestion, deleteQuestion, getExamScores, getExamStatistics, exportExamScores } from '@/api/exam'

// 考试列表数据
const examList = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 当前页码
const currentPage = ref(1)
// 每页条数
const pageSize = ref(10)
// 总条数
const total = ref(0)
// 加载状态
const loading = ref(false)

// 对话框状态
const editDialogVisible = ref(false)
const dialogType = ref('add')

// 考试表单数据
const examForm = ref({
  id: '',
  title: '',
  category: '',
  duration: 60,
  totalScore: 100,
  passScore: 60,
  startTime: '',
  endTime: '',
  status: 1,
  description: ''
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入考试名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  duration: [{ required: true, message: '请输入考试时长', trigger: 'blur' }],
  totalScore: [{ required: true, message: '请输入总分', trigger: 'blur' }],
  passScore: [{ required: true, message: '请输入及格分', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 题目管理相关
const questionDialogVisible = ref(false)
const currentExamId = ref('')
const questions = ref([])
const questionEditDialogVisible = ref(false)
const currentQuestion = ref({
  id: '',
  examId: '',
  type: 'single',
  title: '',
  score: 5,
  options: [{ content: '' }, { content: '' }],
  correctAnswer: '',
  correctAnswers: [],
  referenceAnswer: ''
})

// 题目表单验证规则
const questionRules = {
  type: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
  title: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
  score: [{ required: true, message: '请输入分数', trigger: 'blur' }]
}

// 成绩管理相关
const scoreDialogVisible = ref(false)
const scores = ref([])
const scoreStats = ref({
  total: 0,
  passed: 0,
  average: 0
})

// 加载考试列表
const loadExamList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value
    }
    
    const res = await getExamPage(params)
    examList.value = res.records || []
    total.value = res.total || 0
  } catch (error) {
    ElNotification.error('获取考试列表失败')
    console.error('Failed to load exam list:', error)
  } finally {
    loading.value = false
  }
}

// 搜索考试
const searchExams = () => {
  currentPage.value = 1
  loadExamList()
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  currentPage.value = 1
  loadExamList()
}

// 刷新数据
const refreshData = () => {
  loadExamList()
}

// 打开新增对话框
const openAddDialog = () => {
  dialogType.value = 'add'
  examForm.value = {
    id: '',
    title: '',
    category: '',
    duration: 60,
    totalScore: 100,
    passScore: 60,
    startTime: '',
    endTime: '',
    status: 1,
    description: ''
  }
  editDialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = async (row) => {
  dialogType.value = 'edit'
  try {
    const res = await getExamById(row.id)
    examForm.value = { ...res }
    editDialogVisible.value = true
  } catch (error) {
    ElNotification.error('获取考试详情失败')
    console.error('Failed to get exam detail:', error)
  }
}

// 关闭对话框
const closeDialog = () => {
  editDialogVisible.value = false
}

// 保存考试
const saveExam = async () => {
  try {
    await saveOrUpdateExam(examForm.value)
    ElNotification.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
    closeDialog()
    loadExamList()
  } catch (error) {
    ElNotification.error(dialogType.value === 'add' ? '新增失败' : '编辑失败')
    console.error('Failed to save exam:', error)
  }
}

// 删除考试
const deleteExam = async (id) => {
  try {
    const result = await ElMessageBox.confirm('确定要删除该考试吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    if (result === 'confirm') {
      await deleteExams([id])
      ElNotification.success('删除成功')
      loadExamList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElNotification.error('删除失败')
      console.error('Failed to delete exam:', error)
    }
  }
}

// 管理题目
const manageQuestions = async (examId) => {
  currentExamId.value = examId
  try {
    const res = await getExamQuestions(examId)
    questions.value = res || []
    questionDialogVisible.value = true
  } catch (error) {
    ElNotification.error('获取题目列表失败')
    console.error('Failed to load questions:', error)
  }
}

// 刷新题目
const refreshQuestions = async () => {
  try {
    const res = await getExamQuestions(currentExamId.value)
    questions.value = res || []
  } catch (error) {
    ElNotification.error('刷新题目列表失败')
    console.error('Failed to refresh questions:', error)
  }
}

// 打开题目编辑对话框
const openQuestionEditDialog = (question) => {
  if (question) {
    // 编辑题目
    currentQuestion.value = {
      ...question,
      options: question.options ? JSON.parse(question.options) : [{ content: '' }, { content: '' }],
      correctAnswer: question.correctAnswer || '',
      correctAnswers: question.correctAnswers ? JSON.parse(question.correctAnswers) : [],
      referenceAnswer: question.referenceAnswer || ''
    }
  } else {
    // 新增题目
    currentQuestion.value = {
      id: '',
      examId: currentExamId.value,
      type: 'single',
      title: '',
      score: 5,
      options: [{ content: '' }, { content: '' }],
      correctAnswer: '',
      correctAnswers: [],
      referenceAnswer: ''
    }
  }
  questionEditDialogVisible.value = true
}

// 添加选项
const addOption = () => {
  currentQuestion.value.options.push({ content: '' })
}

// 删除选项
const removeOption = (index) => {
  currentQuestion.value.options.splice(index, 1)
  
  // 更新正确答案
  if (currentQuestion.value.type === 'single') {
    const correctIndex = currentQuestion.value.correctAnswer.charCodeAt(0) - 65
    if (correctIndex >= index) {
      currentQuestion.value.correctAnswer = correctIndex === index ? '' : String.fromCharCode(65 + correctIndex - 1)
    }
  } else if (currentQuestion.value.type === 'multiple') {
    const newCorrectAnswers = currentQuestion.value.correctAnswers
      .map(ans => {
        const ansIndex = ans.charCodeAt(0) - 65
        if (ansIndex > index) {
          return String.fromCharCode(65 + ansIndex - 1)
        } else if (ansIndex < index) {
          return ans
        }
        return null
      })
      .filter(ans => ans !== null)
    currentQuestion.value.correctAnswers = newCorrectAnswers
  }
}

// 保存题目
const saveQuestion = async () => {
  try {
    // 处理题目数据
    const questionData = {
      ...currentQuestion.value,
      options: JSON.stringify(currentQuestion.value.options),
      correctAnswers: JSON.stringify(currentQuestion.value.correctAnswers)
    }
    
    await saveOrUpdateQuestion(questionData)
    ElNotification.success(currentQuestion.value.id ? '编辑成功' : '新增成功')
    questionEditDialogVisible.value = false
    refreshQuestions()
  } catch (error) {
    ElNotification.error(currentQuestion.value.id ? '编辑失败' : '新增失败')
    console.error('Failed to save question:', error)
  }
}

// 删除题目
const deleteQuestionById = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该题目吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteQuestion(id)
    ElNotification.success('删除成功')
    refreshQuestions()
  } catch (error) {
    if (error !== 'cancel') {
      ElNotification.error('删除失败')
      console.error('Failed to delete question:', error)
    }
  }
}

// 查看成绩
const viewScores = async (examId) => {
  currentExamId.value = examId
  try {
    // 获取成绩列表
    const params = {
      examId: examId,
      page: 1,
      size: 1000 // 获取所有成绩
    }
    const res = await getExamScores(params)
    scores.value = res.records || []
    
    // 获取统计信息
    const stats = await getExamStatistics(examId)
    scoreStats.value = stats || { total: 0, passed: 0, average: 0 }
    
    scoreDialogVisible.value = true
  } catch (error) {
    ElNotification.error('获取成绩失败')
    console.error('Failed to load scores:', error)
  }
}

// 导出成绩
const exportScores = async () => {
  try {
    const res = await exportExamScores(currentExamId.value)
    // 创建下载链接
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `考试成绩_${currentExamId.value}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    ElNotification.success('导出成功')
  } catch (error) {
    ElNotification.error('导出失败')
    console.error('Failed to export scores:', error)
  }
}

// 格式化日期
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return ''
  return new Date(cellValue).toLocaleDateString()
}

// 格式化日期时间
const formatDateTime = (row, column, cellValue) => {
  if (!cellValue) return ''
  return new Date(cellValue).toLocaleString()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadExamList()
}

// 当前页变化
const handleCurrentChange = (current) => {
  currentPage.value = current
  loadExamList()
}

// 页面加载时获取数据
onMounted(() => {
  loadExamList()
})
</script>

<style scoped>
.exam-list-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.question-management,
.score-management {
  padding: 20px 0;
}

.question-toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.score-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.score-stats {
  display: flex;
  gap: 20px;
  color: #666;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-bar {
    flex-direction: column;
  }
  
  .action-buttons {
    flex-wrap: wrap;
  }
  
  .score-header {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
}
</style>